import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken ,getPage,getMenu} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import send from '@/api/service'


import { constantRoutes } from '@/router'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login','/404'] // no redirect whitelist
 router.beforeEach(async(to, from, next) => {
  // start progress bar
   NProgress.start()
   // set page title
   document.title = getPageTitle(to.meta.title)

   // determine whether the user has logged in
   const hasToken = getToken()
   if (hasToken) {
   //菜单存在时直接下一步
   if (store.getters.page.length!=0) {
  
    // if (sendload(to.meta.menuid,to.meta.url)) {
    //   next()
    // }
     next()
   }

   // 有token，刷新时store.getters.page.length==0，此时用存储菜单
   else {
    
     let menu = getMenu()
     if (menu&&menu.length){
      //  console.log("3")
       let page =[].concat(menu)
       store.dispatch('permission/generateRoutes',page).then((routes) =>{
      
         router.options.routes=(routes)
         
         router.$addRoutes(routes)
         router.replace(to.path)
        //  console.log(routes,"111")
       })
       next()
     } else if(to.path!=="/login"){
      //  console.log("4")
       next(`/login`)
     }
   }
 } else {/* has no token*/
   if (whiteList.indexOf(to.path) !== -1) {
    //  console.log("5")
     next()
   } else if(to.path!=="/login"){
    //  console.log("6")
     next(`/login`)
   }
 }

})
function  sendload(id,url){
  let flag = false
  let postData = {
    "menuid": id,
  }
  send(postData,url).then(response => {
    // console.log(response)
    const { data }=response;
    if (!data) {
      this.$message('验证权限失败')
    }
    const { funeralDead,familyMember,familyAgent } = data
  }).catch(error => {
    this.$message(error)
  })
  return flag
}
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
